/**
 * 解析行文件，转成数组格式
 * @param {*} data 
 * @returns 
 */
export const parseFiles = (inpuData, fileName) => {
    // 使用正则表达式匹配文件后缀
    const isINI = /\.ini$/.test(fileName);
    const isBKP = /\.bkp$/.test(fileName);
    const keyValuePairs = {};
    // 1 代bkp文件 
    if (isBKP) {
        return parseBkp(inpuData)
    }
    // 2 代 ini文件
    if (isINI) {
        return parseIni(inpuData)
    }
    return keyValuePairs;
}

// 检验文件中的指标值是否在标准范围内
export const checkFiles = (resultData, currentfileRules) => {
    // console.log(`resultData`,resultData,Object.keys(resultData))
    const errorArray = [];
    const okArray = [];
    const jiaoyankeyObj = currentfileRules.reduce((total, cur) => {
        if (!total[cur.keyGroupName]) {
            total[cur.keyGroupName] = {};
        }
        total[cur.keyGroupName][cur.key] = cur.equal;
        return total;
    }, {});
    // console.log(`jiaoyankeyObj`,jiaoyankeyObj,Object.keys(jiaoyankeyObj))
    let errorRows = [];
    Object.keys(jiaoyankeyObj).forEach((item) => {
        let key_group_name = item;
        Object.keys(jiaoyankeyObj[key_group_name]).forEach((key) => {

            if (!resultData[key_group_name]) {
                errorRows.push(item);
            } else {
                // console.log(`jiaoyankeyObj[key_group_name]`,jiaoyankeyObj[key_group_name])
                let fileParamVal = resultData[key_group_name][key]
                if (fileParamVal && fileParamVal != jiaoyankeyObj[key_group_name][key]) {
                    errorArray.push({ key, value: fileParamVal, status: '1', expected: jiaoyankeyObj[key_group_name][key], remarks: '' });
                } else {
                    okArray.push({ key, value: fileParamVal, status: '0', expected: jiaoyankeyObj[key_group_name][key], remarks: '' });
                }
            }
        });
    });
    // console.log(`errorRows`,errorRows)
    const allObj = {
        'checkStatus': errorArray.length >= 1 ? '1' : '0',
        'checkData': [...errorArray, ...okArray]
    }
    return allObj
}


function parseIni(fileContent) {
    const lines = fileContent.split('\n');
    const resultMap = {}
    let currentGroupKey
    lines.forEach(item => {
        if (item.startsWith('[')) {
            currentGroupKey = item.trim()
            resultMap[item.trim()] = {}
        } else {
            if (resultMap[currentGroupKey]) {
                if (item) {
                    let key = item.split('=')[0].trim()
                    let value = item.split('=')[1]
                    if (key) {
                        // if (!value) {
                            // console.log(`item`,item)
                        //     value = ''
                        // }
                        resultMap[currentGroupKey][key.trim()] = value.trim()
                    }
                }
            }
        }
    })
    return resultMap
}
function parseBkp(fileContent) {
    // 按行分割数据
    const lines = fileContent.split('\n');
    // console.log(`lines`,lines)
    // return
    const resultMap = {}
    let currentGroupKey
    lines.forEach(item => {
        if (item.startsWith('[')) {
            if (item !== '[Header]') {
                resultMap[item.trim()] = {}
                currentGroupKey = item.trim()
            }
        } else {
            if (!item.startsWith('Address')) {
                if (resultMap[currentGroupKey]) {
                    if (item) {
                        const [key, value] = item.split(/\s{2,}/).slice(0, 2);
                        // console.log(`value`,value)
                        resultMap[currentGroupKey][key] = value
                    }
                }
            }
        }
    })
    return resultMap
}
// 请求并发控制
export function startLimit(paramArr = [], request = async () => { }, num = 5, callback = () => { }) {
    let recusion = (resolve) => {
        if (paramArr.length == 0) {
            return resolve()
        }
        let param = paramArr.shift()
        request(param).then(res => {
            param.data = res
            recusion(resolve)
        })
    }
    return Promise.all(Array.from({ length: num }, (v, index) => {
        return new Promise((resolve, reject) => {
            recusion(resolve)
        })
    })).then(() => {
        callback()
    })
}

export async function calculateHash(file) {
    return 'hashHex'
    const hashBuffer = await crypto.subtle.digest('SHA-256', await file.arrayBuffer());
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
    return hashHex;
}